$(function(){
    

    });

function getBallStatsIndicator()
{
 
    sendRequest.setAction('getBallStatsIndicator');
    sendRequest.setSendParameters({
        gameID:GameID
    });
    $('#mask').load(sendRequest.serverURL,sendRequest.getSendData(),function (commentatorContent)
    {

        $('body').append($("#mask").html());
        $("#mask").empty();
        $("#mask").unbind();

        setUpBallStatsContainer();
       
    });
}

function setUpBallStatsContainer()
{
    $(".trigger").click(function(){
        $(".panel").toggle("fast");
        $(this).toggleClass("active");
        return false;
    });

    $(".panel").toggle("fast");
    $(this).toggleClass("active");

    setTimeout(function() {
        $(".panel").toggle("fast");
        $(this).toggleClass("active");  
    },3500);
}

function refreshBallStatsIndicator()
{
    $('.trigger').remove();
    $('.panel').remove();
    getBallStatsIndicator();
}


function openBallByBallCommentaryWindow()
{

    modalWindowHandler.setWindowPosition('top');
    modalWindowHandler.setModalWindowTitle("Ball By Ball Commentary");
    modalWindowHandler.setContent('getBallByBallCommentaryForm');
    $( "#modalDialogWindow" ).empty();
    $( "#modalDialogWindow" ).html("<div id='modalWindowContent'></div>");
    $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
    //modalWindowHandler.openModalWindow();
    $( "#modalDialogWindow" ).dialog('open');
    //modalWindowHandler.AJAXCallbackFunction = ("setUpAddTeamModalWindow");
    // modalWindowHandler.openModalWindow();
    //setUpAddPlayerModalWindow();
    $( "#modalDialogWindow" ).dialog({
        zIndex: 3999
    });
    modalWindowHandler.setWindowWidth('890');
    $("#modalDialogWindow").dialog( "option", "buttons", {
        "Edit Previous Ball Commentary": function() {
        },
        "Insert Ball Commentary": function() {


        },
        "Cancel": function() {
            $("#modalDialogWindow").dialog('close');
            jQuery('.errorMessageDiv').html('');
            $('.trigger').remove();
            $('.panel').remove();
        }
    });

    $( "#modalDialogWindow" ).bind( "dialogbeforeclose", function(event, ui) {
    
        jQuery('.errorMessageDiv').html('');
        $('.trigger').remove();
        $('.panel').remove();

    });
    loadBallByBallCommentaryWindowContent();

}

function loadBallByBallCommentaryWindowContent()
{
    modalWindowHandler.setWindowPosition('top');
    sendRequest.setAction('getBallByBallCommentaryForm');
    sendRequest.setSendParameters({
        gameID:GameID
    });
    $("#mask").load(sendRequest.serverURL,sendRequest.getSendData(),function (commentatorContent)
    {
        $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
        $( "#modalDialogWindow" ).children("#modalWindowContent").hide();
        $( "#modalDialogWindow" ).children("#modalWindowContent").delay(500).html($("#mask").html()).fadeIn('slow');
        $("#mask").empty();
        $(".errorMessageDiv").hide();
        $("#mask").unbind();
        modalWindowHandler.setWindowPosition('top');
        $("#modalDialogWindow").scrollTop();
        setUpBallByBallCommentaryWindow();

        //setUpGameInsertGameModalWindow()
        getBallStatsIndicator();
    });
}

function deactivateGame()
{

    sendRequest.setAction('deactivateGame');
    sendRequest.setSendParameters({
        gameID:GameID
    });
    $("#mask").load(sendRequest.serverURL,sendRequest.getSendData(),function (commentatorContent)
    {
        $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
        $( "#modalDialogWindow" ).children("#modalWindowContent").hide();
        $( "#modalDialogWindow" ).children("#modalWindowContent").delay(500).html($("#mask").html()).fadeIn('slow');
        $("#mask").empty();
        $(".errorMessageDiv").hide();
        $("#mask").unbind();
    });
}

function setUpBallByBallCommentaryWindow()
{
    if ($("input[name='isGameFinished']").val() == '0')
    {
        setUpCurrentBallCommentaryWindow();
    }
    else
    {
        setUpFinalizedGameCommentaryWindow();
    }
}

function setUpFinalizedGameCommentaryWindow()
{
    $( "#modalDialogWindow" ).bind( "dialogbeforeclose", function(event, ui) {
        jQuery('.errorMessageDiv').html('');
        $('.trigger').remove();
        $('.panel').remove();
    });
    $("#modalDialogWindow").dialog( "option", "buttons", {
        "Finish Game": function() {
            var finalResultCommentary = $(":input[id=finalResultCommentary]");

            var bValid = true;
            finalResultCommentary.removeClass('ui-state-error');

            bValid = bValid && formValidator.checkLength(finalResultCommentary,"the final result commentary",3,100);
            bValid = bValid && formValidator.checkRegexp(finalResultCommentary,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The final result commentary field only allows alphanumeric characters (a-z 0-9).");
               

            if (bValid) {
                sendRequest.setAction('finalizeGame');

                postVars = {
                    'gameID':GameID,
                    'finalResultCommentary':finalResultCommentary.val()
                };
                sendRequest.setSendParameters(postVars);
                var hiddenResponseDiv = $(".responseDiv");
                hiddenResponseDiv.load(sendRequest.serverURL, sendRequest.getSendData(), function(){
                    hiddenResponseDiv.unbind();
                    var finalResponse = (hiddenResponseDiv.html()).replace(/^\s*|\s*$/g,'');
                    hiddenResponseDiv.show();
                    if (finalResponse == '1')
                    {
                        $("#modalDialogWindow").dialog('close');
                        jQuery('.errorMessageDiv').html('');
                        $('.trigger').remove();
                        $('.panel').remove();
                        deactivateGame();
                    }
                    else
                    {
                        finalResultCommentary.addClass('ui-state-error');
                        formValidator.updateErrorMessage("Finalizing game result has failed. Please contact your software administrator.");
                    }
                });


            }

        },
        "Cancel": function() {
            $("#modalDialogWindow").dialog('close');
            jQuery('.errorMessageDiv').html('');
            $('.trigger').remove();
            $('.panel').remove();
        }
    });
}

function setUpCurrentBallCommentaryWindow()
{

    prepareCanvas();

    $("#commentarytabs").tabs();
    var customExtraType = $(":input[id=customExtraType]");
    $("#container_batsmanFacing").buttonset();
    $("#container_runsScored").buttonset();
    $("#container_shotType").buttonset();
    $("#container_bowlerTypeSelector").buttonset();
    $(".bowlingPlayerTypes").buttonset();
    $("#container_ballSelectorType").buttonset();
    $("#container_dismissalType").buttonset();
    $("#legSpinDeliveryTypeContainer").buttonset();
    $("#offSpinDeliveryTypeContainer").buttonset();
    $("#fastBowlingDeliveryTypeContainer").buttonset();
    $("#container_extraType").buttonset();
    $("#container_dismissalFeilder").buttonset();
    $("#isDismissed").button();
    

    $("#bowlingStatContainer .ui-button").css('width','185px');
    // $("#dismissalStatContainer .ui-button").css('width','150px');
    //    //jQuery("#battingStatContainer .ui_button").css('width','150px');
    //    jQuery("#bowlerTypeSelectorContainer .ui_button").css('width','150px');
    //    jQuery("#container_bowlerAttacking .ui_button").css('width','150px');
    //
    jQuery('#container_batsmanFacing .ui-button').css('width','185px');
    jQuery('#container_shotType .ui-button').css('width','185px');
    //    jQuery('#container_ballSelectorType .ui-button').css('width','150px');
    //    jQuery('#legSpinDeliveryTypeContainer .ui-button').css('width','150px');
    //    jQuery('#offSpinDeliveryTypeContainer .ui-button').css('width','150px');
    //    jQuery('#fastBowlingDeliveryTypeContainer .ui-button').css('width','150px');
    jQuery('#dismissalDetailsContainer .ui-button').css('width','185px');
    jQuery("#container_dismissalFeilder .ui_button").css('width','185px');
    //    $("#container_extraType .ui-button").css('width','150px');
    $("#ballComentary .ui-button").css('font-size',"85%");
    $('#customShotTypeContainer').hide();
    $('#customExtraTypeContainer').hide();
    $("#customDismissalTypeContainer").hide();
    $("#dismissalDetailsContainer").hide();
    $(".bowlingPlayerTypes").hide();
    $(".bowlingPlayerTypes:first").show();
    $(".loadingScreen").hide();

    $( "#slider-ballSpeed" ).slider({
        range: "min",
        step: 0.1,
        value: 100,
        min: 0,
        max: 200,
        slide: function( event, ui ) {
            $( "#ballSpeed" ).val( ui.value+" km/h" );
            $( "#ballSpeed-mph" ).val( Math.round((parseFloat(ui.value*0.621371192)*100))/100+" mph" );

        }
    });
    $( "#ballSpeed" ).val( $( "#slider-ballSpeed" ).slider( "value" ) + " km/h" );
    $( "#ballSpeed-mph" ).val( Math.round(parseFloat($( "#slider-ballSpeed" ).slider( "value" )*0.621371192)*100)/100 + " mph" );
                

    var legSpinDeliveryTypeContainer = $('#legSpinDeliveryTypeContainer');
    var offSpinDeliveryTypeContainer = $('#offSpinDeliveryTypeContainer');
    var fastBowlingDeliveryTypeContainer = $('#fastBowlingDeliveryTypeContainer');
    var customDeliveryTypeContainer = $('#customDeliveryTypeContainer');
    offSpinDeliveryTypeContainer.hide();
    fastBowlingDeliveryTypeContainer.hide();
    customDeliveryTypeContainer.hide();
    
  
    $("#container_shotType").change(function(){
        //   $('#customShotTypeContainer').show('fast');
        if ($("input:radio[name=shotType]:checked").val() == 'other')
        {
            $('#customShotTypeContainer').show('scale',{
                percent: 100
            },500);
        }
        else
        {
            $('#customShotTypeContainer').fadeOut('fast');
        }

    });


    $("#container_extraType").change(function(){
        //   $('#customShotTypeContainer').show('fast');
        if ($("input:radio[name=extraType]:checked").val() == 'other')
        {
            $('#customExtraTypeContainer').show('scale',{
                percent: 100
            },500);
        }
        else
        {
            $('#customExtraTypeContainer').fadeOut('fast');
        }

    });

    $("#container_bowlerTypeSelector").change(function(){

        $(".bowlingPlayerTypes").hide();
        $("#"+$("input:radio[name=bowlerTypeSelector]:checked").val()).show('drop',{
            percent: 100
        },500);

    });
    $("#container_ballSelectorType").change(function(){
        //  $('div').append($("input:radio[name=ballSelectorType]:checked").val());
        if ($("input:radio[name=ballSelectorType]:checked").val() == 'legspin')
        {
            var otherContainers = jQuery([]).add(offSpinDeliveryTypeContainer).add(fastBowlingDeliveryTypeContainer).add(customDeliveryTypeContainer);
            otherContainers.hide();
            legSpinDeliveryTypeContainer.show('drop',{
                percent: 100
            },500);
        }
        else if ($("input:radio[name=ballSelectorType]:checked").val() == 'offspin')
        {
            var otherContainers = jQuery([]).add(legSpinDeliveryTypeContainer).add(fastBowlingDeliveryTypeContainer).add(customDeliveryTypeContainer);
            otherContainers.hide();
            offSpinDeliveryTypeContainer.show('drop',{
                percent: 100
            },500);
        }
        else if ($("input:radio[name=ballSelectorType]:checked").val() == "fastbowling")
        {
            var otherContainers = jQuery([]).add(legSpinDeliveryTypeContainer).add(offSpinDeliveryTypeContainer).add(customDeliveryTypeContainer);
            otherContainers.hide();
            fastBowlingDeliveryTypeContainer.show('drop',{
                percent: 100
            },500);
        }
        else if ($("input:radio[name=ballSelectorType]:checked").val() == 'other')
        {
            var otherContainers = jQuery([]).add(legSpinDeliveryTypeContainer).add(offSpinDeliveryTypeContainer).add(fastBowlingDeliveryTypeContainer);
            otherContainers.hide();
            customDeliveryTypeContainer.show('scale',{
                percent: 100
            },500);
        }
    });

    $("#isDismissed").change(function(){

        if ($('#isDismissed').is(':checked'))
        {
            //  $('input[name="runsScored"]').attr('checked', false);
            var $runsScored = $('input:radio[name=runsScored]');
   
            jQuery("input:radio[name=runsScored]:eq(0)").attr('checked', 'checked');
            jQuery("input:radio[name=shotType]:eq(0)").attr('checked', 'checked');
            jQuery("input:radio[name=extraType]:eq(0)").attr('checked', 'checked');

            $("#container_runsScored").buttonset( "refresh" );
            $("#container_extraType").buttonset( "refresh" );
            $("#container_shotType").buttonset( "refresh" );
            $( "#container_runsScored" ).buttonset({
                disabled: true
            });
            $( "#container_shotType" ).buttonset({
                disabled: true
            });
            $("#container_extraType").buttonset({
                disabled: true
            });
            $('#customShotTypeContainer').hide();
            $('#customExtraTypeContainer').hide();
            $("#dismissalDetailsContainer").show('blind',{},500);

        }
        else
        {
            $( "#container_runsScored" ).buttonset({
                disabled: false
            });
            $( "#container_shotType" ).buttonset({
                disabled: false
            });
            $("#container_extraType").buttonset({
                disabled: false
            });
            jQuery("input:radio[name=dismissalType]:eq(0)").attr('checked', 'checked');
            $("#container_dismissalType").buttonset( "refresh" );
            $('input[id=customDismissalType]').val('');
            $("#customDismissalTypeContainer").hide();
            $("#dismissalDetailsContainer").hide('blind',{},500);
        }

    });


    $("#container_dismissalType").change(function(){
        //  $('div').append($("input:radio[name=ballSelectorType]:checked").val());
        if ($("input:radio[name=dismissalType]:checked").val() == 'other')
        {

            $("#customDismissalTypeContainer").show('scale',{
                percent: 100
            },500);
        }
        else
        {
            $("#customDismissalTypeContainer").fadeOut();
        }
     

    });

    $(".ui-dialog-buttonpane button:contains('Edit Previous Ball Commentary')").button({
        disabled: true
    });
    $( ".errorMessageDiv" ).hide();
    $(".responseDiv").hide();
         
    $(".ui-dialog-buttonpane button:contains('Insert Ball Commentary')").click(function(){
        
        var batsmanFacing = $("input:radio[name=batsmanFacing]:checked");
        var runsScored = $("input:radio[name=runsScored]:checked");
        var shotType = $("input:radio[name=shotType]:checked");
        var customShotType = $("input[id=customShotType]");
        var bowlerSelector =  $("input:radio[name=bowlerTypeSelector]:checked");
        var bowlerBowling = $("input:radio[name=bowlerAttacking]:checked");
        var deliverySelectorType = $("input:radio[name=ballSelectorType]:checked");
        var deliveryType = $("input:radio[name=deliveryType]:checked");
        var customDeliveryType = $(":input[id=customDeliveryType]");
        var extraType = $("input:radio[name=extraType]:checked");
        var customExtraType = $(":input[id=customExtraType]");
        var ballSpeed = jQuery(':input[id=ballSpeed]');
        var isDissmissed = null;
        if ($('#isDismissed').is(':checked'))
        {
            isDissmissed = true;
        }
        else
        {
            isDissmissed = false;
        }
        var dismissalType = $("input:radio[name=dismissalType]:checked");
        var customDismissalType = $(":input[id=customDismissalType]");
        var dismissalFielder =  $("input:radio[name=dismissalFeilder]:checked");
        var ballCommentary = $(":input[id=ballCommentary]");


        var allFields = jQuery([]).add(customShotType).add(customDeliveryType).add(customExtraType).add(customDismissalType).add(ballCommentary);
        var bValid = true;
        allFields.removeClass('ui-state-error');
            
        bValid = bValid && formValidator.checkRegexp(batsmanFacing,/^\s*(\+|-)?\d+\s*$/,"The batsman facing selector only accepts player IDs which are integers (0-9).");
        var CurrentBatsManFacingID = batsmanFacing.val();
        bValid = bValid && formValidator.checkRegexp(runsScored,/^\s*(\+|-)?\d+\s*$/,"The runs scored selector only accepts runs numbers which are integers (0-9).");
        var CurrentRunsScored = runsScored.val();
        var CurrentShotType = $('input[name=shotType]:checked + label').text();
        if (shotType.val() == 'other')
        {
            bValid = bValid && formValidator.checkLength(customShotType,"the custom shot type",5,100);
            bValid = bValid && formValidator.checkRegexp(customShotType,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The custom shot type field only allows alphanumeric characters (a-z 0-9).");
            CurrentShotType = customShotType.val();
        }
        var CurrentBallSpeed = ballSpeed.val();
        bValid = bValid && formValidator.checkLength(ballSpeed,"the ball speed",4,10);
        var CurrentBowlerBowling = bowlerBowling.val();
        bValid = bValid && formValidator.checkRegexp(bowlerBowling,/^\s*(\+|-)?\d+\s*$/,"The batsman bowling selector only accepts player IDs which are integers (0-9).");
        var CurrentDeliveryType = $('input[name=deliveryType]:checked + label').text()+" ("+deliverySelectorType.val()+")   "+CurrentBallSpeed;
        if (deliverySelectorType.val() == 'other')
        {
            CurrentDeliveryType = customDeliveryType.val()+"    "+CurrentBallSpeed;
            bValid = bValid && formValidator.checkLength(customDeliveryType,"the custom delivery type",5,100);
            bValid = bValid && formValidator.checkRegexp(customDeliveryType,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The custom delivery type field only allows alphanumeric characters (a-z 0-9).");
        }
        if (extraType.val() != 'none')
        {
            var CurrentIsExtra = 1;
            var CurrentExtraType = extraType.val();
            if (extraType.val() == 'other')
            {
                CurrentExtraType = customExtraType.val();
                bValid = bValid && formValidator.checkLength(customExtraType,"the custom extra type",5,100);
                bValid = bValid && formValidator.checkRegexp(customExtraType,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The custom extra type field only allows alphanumeric characters (a-z 0-9).");
            }
        }
        else
        {
            var CurrentIsExtra = 0;
            var CurrentExtraType = "";
        }



        if (isDissmissed)
        {
            var CurrentIsDismissed = 1;
            var dismissalTypeText = dismissalType.val();
            if (dismissalType.val() == 'other')
            {
                dismissalTypeText = customDismissalType.val();
                bValid = bValid && formValidator.checkLength(customDismissalType,"the custom dismissal type",5,100);
                bValid = bValid && formValidator.checkRegexp(customDismissalType,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The custom dissmissal type field only allows alphanumeric characters (a-z 0-9).");
            }
            var dismissalFeilderText = dismissalFielder.val();
            var CurrentDismissalType = dismissalTypeText +" ("+dismissalFeilderText+") b("+$('input[name=bowlerAttacking]:checked + label').text()+")";
        }
        else
        {
            var CurrentIsDismissed = 0;
            var CurrentDismissalType = "";
        }

        bValid = bValid && formValidator.checkLength(ballCommentary,"the ball commentary",10,250);
        bValid = bValid && formValidator.checkRegexp(ballCommentary,/^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\s]*$/,"The ball commentary field only allows alphanumeric characters (a-z 0-9).");
        var CurrentBallCommentary = ballCommentary.val();

        if (bValid)
        {
         
            $(".ballByBallStatsCommentaryContainer").hide();
            $(".loadingScreen").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>").fadeIn('slow');

var ClickXJSON = JSON.stringify(clickX);
var ClickYJSON = JSON.stringify(clickY);
var ClickDragJSON = JSON.stringify(clickDrag);
var ballTrajectoryParameters = {'clickX':ClickXJSON,'clickY':ClickYJSON,"clickDrag":ClickDragJSON};
//            var ballTrajectoryToPost = {
//
//            };
            var ballCommentaryDataToPost =
            {
                'commentatorID': $("input[name='commentatorID']").val(),
                'bowlType': CurrentDeliveryType,
                'batShotType':CurrentShotType,
                'runs': CurrentRunsScored,
                'commentary': CurrentBallCommentary,
                'batsmanID': CurrentBatsManFacingID,
                'bowlerID': CurrentBowlerBowling,
                "gameID": GameID,
                'isDismissal':CurrentIsDismissed,
                'dismissalType':CurrentDismissalType,
                "isExtra":CurrentIsExtra,
                "extraType":CurrentExtraType,
                 "trajectoryType":trajectoryType,
                 "ballTrajectoryParameters":ballTrajectoryParameters
            };
//var clickX = new Array();
//var clickY = new Array();
//var clickDrag = new Array();


            sendRequest.setAction('insertBallCommentary');
            sendRequest.setSendParameters(ballCommentaryDataToPost);
            var hiddenResponseDiv = $('.responseDiv');
            $( "#modalDialogWindow" ).children('#loadingScreen').children().empty();
            hiddenResponseDiv.load(sendRequest.serverURL, sendRequest.getSendData(), function(){
                hiddenResponseDiv.unbind();
                //hiddenResponseDiv.show();
                var insertResponse = (hiddenResponseDiv.html()).replace(/^\s*|\s*$/g,'');
                if (insertResponse == '1')
                {
                    $(".ui-dialog-buttonpane button:contains('Insert Ball Commentary')").unbind();
                    $( "#modalDialogWindow" ).children("#modalWindowContent").fadeOut();
                   clickX = [];
                    clickY = [];
                    clickDrag = [];
                    loadBallByBallCommentaryWindowContent();
                // getBallStatsIndicator();
                }
                else if (insertResponse == '2')
                {
                    loadFinalResultWindowContent();
                }
      
                else
                {
                    $(".loadingScreen").hide();
                    $(".ballByBallStatsCommentaryContainer").delay(500).fadeIn('slow');
                    formValidator.updateErrorMessage("Ball Commentary insert has failed. Please contact your software administrator.");
                }


            });
        }

    });


}

function loadFinalResultWindowContent()
{
    sendRequest.setAction('getFinalResultCommentaryForm');
    sendRequest.setSendParameters({
        gameID:GameID
    });
    $("#mask").load(sendRequest.serverURL,sendRequest.getSendData(),function (commentatorContent)
    {
        $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
        $( "#modalDialogWindow" ).children("#modalWindowContent").hide();
        $( "#modalDialogWindow" ).children("#modalWindowContent").delay(500).html($("#mask").html()).fadeIn('slow');
        $("#mask").empty();
        $(".errorMessageDiv").hide();
        $("#mask").unbind();
        setUpBallByBallCommentaryWindow();
        //setUpGameInsertGameModalWindow()
        getBallStatsIndicator();
    });
}